package com.pb.service.boot.config;

import com.alibaba.fastjson.JSON;
import com.pb.infra.oth.entity.common.Result;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author:廖昊源
 * @create: 2023-03-16 09:44
 * @Description: 上传的文件类型校验
 */
public class FileHeaderCheckInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 判断是否为文件上传请求
        if (request != null && request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = multipartRequest.getFileMap();
            Iterator<String> iterator = files.keySet().iterator();
            while (iterator.hasNext()) {
                String formKey = (String) iterator.next();
                MultipartFile multipartFile = multipartRequest.getFile(formKey);
                String filename = multipartFile.getOriginalFilename();
                byte[] file = multipartFile.getBytes() ;

                // 获取字节流前8字节，差不多够了，不行再加
                int HEADER_LENGTH = 8 ;

                if(file.length>HEADER_LENGTH){
                    //转成16进制
                    StringBuilder sb = new StringBuilder();
                    for(int i=0;i<HEADER_LENGTH;i++){
                        int v = file[i] & 0xFF;
                        String hv = Integer.toHexString(v);
                        if (hv.length() < 2) {
                            sb.append(0);
                        }
                        sb.append(hv);
                    }

                    boolean isFound = false ;
                    String fileHead = sb.toString().toUpperCase() ;
                    List<String> headerList = FileHeaderHelper.getInstance().getHeaderList() ;
                    for(String header : headerList){
                        if(fileHead.startsWith(header)){
                            isFound = true ;
                            break ;
                        }
                    }
                    if(!isFound){
//                        throw new BaseRunException("上传文件有异常，已被系统禁止！") ;
                        System.out.println("文件名为《"+filename+"》的文件，类型异常，已被系统禁止！头部信息："+fileHead);
                        Result result = Result.error("-1", "文件名为《"+filename+"》的文件，类型异常，已被系统禁止！");

                        response.setCharacterEncoding("UTF-8");
                        response.setHeader("Content-Type", "application/json");
                        response.setHeader("Access-Control-Allow-Credentials", "true");
                        response.setHeader("Access-Control-Allow-Methods", "GET, POST");
                        response.setHeader("Access-Control-Allow-Origin", "*");
                        response.setHeader("Access-Control-Max-Age", "3600");
                        //        response.setHeader("Content-type", "application/json;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.setContentType("application/json;charset=UTF-8");
                        //        ServletOutputStream out = null;
                        PrintWriter writer=null;
                        try {
                            writer = response.getWriter();
                            writer.write(JSON.toJSONString(result));
                            writer.flush();
                        }catch (IOException ex) {
                        ex.printStackTrace();
                    }finally {
                        if(writer!=null) {
                            writer.close();
                        }
                    }
                       // response.sendRedirect("/sys/common/fileError");
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
    }
}
